<template>
  <div class="app-container">
    <!-- 移动端骨架屏 -->
    <mobile-skeleton 
      v-if="isMobile && loading" 
      :showHeader="true"
      :showSearch="true"
      :searchFields="2"
      :showTable="true"
      :tableColumns="4"
      :tableRows="5"
      :showPagination="true"
    />
    
    <div v-else>
      <el-row :gutter="10" :class="{'mobile-layout': isMobile}">
        <!-- 移动端头部 -->
        <div class="mobile-header" v-if="isMobile">
          <div class="page-title">证书管理</div>
        </div>

        <el-col :span="24">
          <div class="course_content">
            <!-- 桌面端表格视图 -->
            <el-table :data="list" style="width: 100%;margin-top:20px" :header-cell-style="{ 'text-align': 'center' }"
              :cell-style="{ 'text-align': 'center' }" @row-dblclick="handleDow" v-if="!isMobile">
              <el-table-column type="selection" width="45">
              </el-table-column>
              <el-table-column label="岗位认证名称" prop="name" min-width="200">
              </el-table-column>
              <el-table-column label="获证人" prop="user">
              </el-table-column>
              <el-table-column label="证书编号" prop="number" min-width="120">
              </el-table-column>
              <el-table-column label="签发人" prop="issuer">
              </el-table-column>
              <el-table-column label="签发时间" prop="start_time" min-width="120">
              </el-table-column>
              <el-table-column label="有效期" min-width="120" prop="end_time">
              </el-table-column>

              <el-table-column label="操作" align="center" v-if="
                hasPermi([
                  'certification:PostCertificate:download',
                ])
              ">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="handleDow(scope.row)"
                    :style="{ backgroundColor: theme, borderColor: theme, fontWeight: 'bold' }"
                    v-hasPermi="['certification:PostCertificate:download']">查看证书
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 移动端卡片视图 -->
            <div class="mobile-card-view" v-if="isMobile">
              <div v-if="list.length === 0" class="empty-data">
                <i class="el-icon-document"></i>
                <p>暂无数据</p>
              </div>
              
              <el-card v-for="(item, index) in list" :key="index" class="mobile-card" shadow="hover">
                <div slot="header" class="card-header">
                  <div class="cert-title" :style="{ color: theme }">{{ item.name }}</div>
                  <div class="cert-status">
                    <span class="cert-number">{{ item.number }}</span>
                  </div>
                </div>
                <div class="card-content">
                  <div class="cert-info">
                    <div class="info-item">
                      <span class="label">获证人：</span>
                      <span class="value">{{ item.user }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">签发人：</span>
                      <span class="value">{{ item.issuer }}</span>
                    </div>
                  </div>
                  <div class="cert-details" v-if="expandedCards[index]">
                    <div class="details-section">
                      <div class="info-item">
                        <span class="label">签发时间：</span>
                        <span class="value">{{ item.start_time }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">有效期至：</span>
                        <span class="value">{{ item.end_time }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="card-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click.stop="handleDow(item)" 
                      :style="{ backgroundColor: theme, borderColor: theme, width: '80%' }"
                      v-hasPermi="['certification:PostCertificate:download']">
                      <i class="el-icon-document"></i> 查看证书
                    </el-button>
                    <div class="card-toggle">
                      <el-button type="text" size="small" @click.stop="expandCard(index)">
                        {{ expandedCards[index] ? '收起' : '查看详情' }}
                        <i :class="expandedCards[index] ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-card>
              
              <!-- 移动端分页 -->
              <div class="mobile-pagination" v-if="total > 0">
                <div class="mobile-pagination-wrapper">
                  <!-- 第一行：总数和每页条数 -->
                  <div class="pagination-row top-row">
                    <span class="el-pagination__total">共 {{ total }} 条</span>
                    <el-select 
                      v-model="queryParams.page_size" 
                      size="mini" 
                      class="el-pagination__sizes"
                      @change="handleSizeChange">
                      <el-option
                        v-for="item in [10, 20, 30, 50]"
                        :key="item"
                        :label="`${item}条/页`"
                        :value="item">
                      </el-option>
                    </el-select>
                  </div>
                  
                  <!-- 第二行：页码导航 -->
                  <div class="pagination-row bottom-row">
                    <el-pagination
                      background
                      @current-change="handleCurrentChange"
                      :current-page="queryParams.page"
                      :page-size="queryParams.page_size"
                      layout="prev, pager, next, jumper"
                      :total="total">
                    </el-pagination>
                  </div>
                </div>
              </div>
            </div>

            <!-- 桌面端分页 -->
            <pagination v-show="total > 0 && !isMobile" :total="total" :page.sync="queryParams.page"
              :limit.sync="queryParams.page_size" @pagination="getList" />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { getCertificate } from "@/api/vadmin/certification/certification";
import MobileSkeleton from "@/components/MobileSkeleton";

export default {
  name: "Certificate",
  components: { 
    MobileSkeleton 
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      list: [],
      queryParams: {
        // courseId: "",
        page: 1,
        page_size: 10,
      },
      total: 0,
      screenWidth: document.body.clientWidth,
      expandedCards: [],
      mediaQueryList: null,
      isMobile: false
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    }
  },

  created() {
    this.getList();
    // 初始化移动设备状态
    this.isMobile = document.body.clientWidth < 768;
    // 监听屏幕宽度变化
    window.addEventListener('resize', this.handleResize);
  },
  
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除监听器
    window.removeEventListener('resize', this.handleResize);
    
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },

  methods: {
    // 处理屏幕大小变化
    handleResize() {
      this.screenWidth = document.body.clientWidth;
      this.isMobile = this.screenWidth < 768;
    },
    
    // 卡片展开/收起
    expandCard(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    },
    
    // 分页处理
    handleSizeChange(size) {
      this.queryParams.page_size = size;
      this.getList();
    },
    
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
    
    getList() {
      this.loading = true;
      getCertificate(this.queryParams).then((res) => {
        this.list = res.results;
        this.loading = false;
        this.total = res.count;
        // 初始化展开卡片状态
        this.expandedCards = Array(this.list.length).fill(false);
      }).catch(() => {
        this.loading = false;
      });
    },
    handleDow(row) {
      window.open(row.file, "_blank");
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}

/* 移动端样式 */
.mobile-layout {
  .mobile-header {
    position: sticky;
    top: 0;
    z-index: 10;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    padding: 15px;
    margin-bottom: 15px;
    border-radius: 8px;
    
    .page-title {
      font-size: 18px;
      font-weight: 500;
    }
  }
  
  .mobile-card-view {
    margin-top: 15px;
    
    .empty-data {
      text-align: center;
      padding: 40px 0;
      color: #909399;
      
      i {
        font-size: 40px;
        margin-bottom: 10px;
      }
      
      p {
        font-size: 14px;
      }
    }
    
    .mobile-card {
      margin-bottom: 15px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
      transition: all 0.3s;
      
      &:active {
        transform: scale(0.99);
      }
      
      /deep/ .el-card__header {
        padding: 12px 15px;
        border-bottom: 1px solid #f0f0f0;
      }
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .cert-title {
          font-weight: bold;
          font-size: 16px;
          line-height: 1.3;
          flex: 1;
        }
        
        .cert-status {
          display: flex;
          align-items: center;
          
          .cert-number {
            font-size: 12px;
            color: #909399;
            background-color: #f5f7fa;
            padding: 2px 6px;
            border-radius: 4px;
          }
        }
      }
      
      .card-content {
        padding: 10px 0;
        
        .cert-info {
          margin: 10px 0;
          
          .info-item {
            margin: 8px 0;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            
            .label {
              color: #606266;
              margin-right: 5px;
              font-size: 14px;
            }
            
            .value {
              color: #333;
              font-size: 14px;
            }
          }
        }
        
        .cert-details {
          margin-top: 15px;
          background-color: #f8f9fa;
          border-radius: 6px;
          padding: 10px 15px;
          
          .details-section {
            .info-item {
              margin: 8px 0;
            }
          }
        }
        
        .card-actions {
          margin-top: 15px;
          border-top: 1px dashed #ebeef5;
          padding-top: 15px;
          text-align: center;
          
          .el-button {
            margin-bottom: 10px;
          }
          
          .card-toggle {
            text-align: center;
            margin: 8px 0 5px;
            
            .el-button {
              width: 100%;
              padding: 8px 0;
              font-size: 13px;
              margin: 0;
              
              i {
                margin-left: 5px;
                font-weight: bold;
              }
            }
          }
        }
      }
    }
  }
}

/* 移动端分页样式 */
.mobile-pagination {
  margin: 20px 0 30px;
  
  .mobile-pagination-wrapper {
    width: 100%;
    border-radius: 4px;
    background-color: #f8f9fa;
    padding: 10px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    
    .pagination-row {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 8px;
      flex-wrap: wrap;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      &.top-row {
        border-bottom: 1px solid #ebeef5;
        padding-bottom: 8px;
        justify-content: space-around;
      }
      
      &.bottom-row {
        padding-top: 5px;
      }
      
      .el-pagination__total {
        margin: 5px 5px 5px 0;
        font-size: 13px;
        color: #606266;
        font-weight: normal;
        white-space: nowrap;
      }
      
      .el-pagination__sizes {
        width: auto;
        margin: 5px 0;
        
        /deep/ .el-input__inner {
          height: 28px;
          line-height: 28px;
          font-size: 13px;
          border-radius: 4px;
        }
        
        /deep/ .el-input__suffix {
          right: 5px;
        }
        
        /deep/ .el-select-dropdown__item {
          padding: 0 15px;
          height: 34px;
          line-height: 34px;
          font-size: 13px;
        }
      }
      
      /deep/ .el-pagination {
        padding: 0;
        white-space: normal;
        background: transparent;
        text-align: center;
        width: 100%;
        
        &.is-background {
          .btn-next,
          .btn-prev,
          .el-pager li {
            margin: 3px;
            min-width: 28px;
            height: 28px;
            line-height: 28px;
            font-size: 12px;
            font-weight: normal;
            background-color: #fff;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
          }
          
          .el-pager li:not(.disabled).active {
            background-color: var(--theme);
            color: #fff;
            border-color: var(--theme);
          }
        }
        
        .el-pagination__jump {
          margin: 5px 0 5px 10px;
          font-size: 13px;
          color: #606266;
          display: flex;
          align-items: center;
          flex-wrap: nowrap;
          white-space: nowrap;
          
          /deep/ .el-input {
            width: 45px;
            margin: 0 3px;
            
            .el-input__inner {
              height: 28px;
              line-height: 28px;
              padding: 0 3px;
              text-align: center;
              font-size: 13px;
              border-radius: 4px;
            }
          }
        }
      }
    }
  }
}

/* 超小屏幕特殊处理 */
@media screen and (max-width: 360px) {
  .mobile-pagination {
    .mobile-pagination-wrapper {
      padding: 8px 5px;
      
      .pagination-row {
        &.top-row {
          flex-direction: column;
          align-items: center;
          
          .el-pagination__total {
            margin-bottom: 8px;
          }
        }
        
        /deep/ .el-pagination {
          .el-pager {
            li {
              min-width: 26px;
              height: 26px;
              line-height: 26px;
              margin: 2px;
              font-size: 12px;
            }
          }
          
          button,
          .btn-prev,
          .btn-next {
            width: 26px;
            height: 26px;
            line-height: 26px;
            margin: 2px;
          }
          
          .el-pagination__jump {
            margin: 5px 0;
            
            /deep/ .el-input {
              width: 40px;
              
              .el-input__inner {
                height: 26px;
                line-height: 26px;
              }
            }
          }
        }
      }
    }
  }
}
</style>